package com.chookss.login;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.WebCommonActivity;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.mine.entity.AccountEntity;
import com.chookss.mine.set.ChangePassActivity;
import com.chookss.tools.AppUtil;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.RSACoder;
import com.chookss.tools.UUidUtils;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.old.SignUtils;
import com.chookss.view.InitDialog;
import com.chookss.view.listener.ShareDialogListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseAct {

    @BindView(R.id.edPhone)
    EditText edPhone;
    @BindView(R.id.edPassword)
    EditText edPassword;
    @BindView(R.id.edCompany)
    EditText edCompany;
    @BindView(R.id.ivPassword)
    ImageView ivPassword;
    @BindView(R.id.ivChoice)
    ImageView ivChoice;
    @BindView(R.id.tvInit)
    TextView tvInit;
    @BindView(R.id.rlArrow)
    RelativeLayout rlArrow;
    @BindView(R.id.rlPhoneDelete)
    RelativeLayout rlPhoneDelete;
    @BindView(R.id.rlCompanyDelete)
    RelativeLayout rlCompanyDelete;
    @BindView(R.id.ivArrow)
    ImageView ivArrow;
    @BindView(R.id.rcvData)
    RecyclerView rcvData;
    @BindView(R.id.llRegister)
    LinearLayout llRegister;
    @BindView(R.id.llCompany)
    LinearLayout llCompany;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.tvRegister)
    TextView tvRegister;
    boolean cipher = true; //密码是否密文
    boolean isAdd = false; //是否是添加账号
    boolean isFirst = false; //是否引导页进来的，第一次登录
    private String ANDROID_ID = "";
    private boolean isSure = false;//默认没有同意协议
    private String errorMsg = "";//自动登录失败提示语
    private UserAdapter adapter;
    private List<AccountEntity> accountEntityList = new ArrayList<>();
    private String company, phone;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        isAdd = getIntent().getBooleanExtra("isAdd", false);
        isFirst = getIntent().getBooleanExtra("isFirst", false);
        errorMsg = getIntent().getStringExtra("errorMsg");
        company = getIntent().getStringExtra("company");
        phone = getIntent().getStringExtra("phone");
        if (getPackageName().equals("com.zhaofengnum")) {
            edCompany.setText(getResources().getString(R.string.app_name));
            llCompany.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
            llRegister.setVisibility(View.GONE);
        }
        try {
            if (edPassword == null) {
                return;
            }
            edPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }
        edPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (edPhone.getText().toString().equals("13300000000")) {
                    edCompany.setText(getResources().getText(R.string.test_company1));
                }else if(edPhone.getText().toString().equals("13503825592")){
                    edCompany.setText(getResources().getText(R.string.test_company2));
                }
            }
        });
        edCompany.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {//获得焦点
                    rlCompanyDelete.setVisibility(View.VISIBLE);
                    rcvData.setVisibility(View.GONE);
                    ivArrow.setBackgroundResource(R.drawable.iv_xiala_24);
                } else {//未获得焦点
                    rlCompanyDelete.setVisibility(View.GONE);
                }
            }
        });
        edPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {//获得焦点
                    rlPhoneDelete.setVisibility(View.VISIBLE);
                    rcvData.setVisibility(View.GONE);
                    ivArrow.setBackgroundResource(R.drawable.iv_xiala_24);
                } else {//未获得焦点
                    rlPhoneDelete.setVisibility(View.GONE);
                }
            }
        });
        ivChoice.setBackgroundResource(R.drawable.icon_no_choice_48);
        tvInit.setText("已阅读并同意");
        SpannableString spStr = new SpannableString("《用户协议》和《隐私政策》");
        String s1 = "《用户协议》";
        String s2 = "《隐私政策》";
        ClickableSpan clickSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(LoginActivity.this,
                        WebCommonActivity.class);
                intent.putExtra("title", "用户协议");
                if (getPackageName().equals("com.zhaofengnum")) {
                    intent.putExtra("url", "http://dev.zhongyuanliantuo.com:38012/zhaofeng_license.html");
                } else {
                    intent.putExtra("url", Urls.license);
                }
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
                ds.setColor(getResources().getColor(R.color.main_color));
            }
        };
        ClickableSpan clickSpan2 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(LoginActivity.this,
                        WebCommonActivity.class);
                intent.putExtra("title", "隐私政策");
                if (getPackageName().equals("com.zhaofengnum")) {
                    intent.putExtra("url", "file:///android_asset/zhaofeng_privacy.html");
                } else {
                    intent.putExtra("url", "file:///android_asset/chookss_privacy.html");
                }
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
                ds.setColor(getResources().getColor(R.color.main_color));
            }
        };
        spStr.setSpan(clickSpan, 0, s1.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spStr.setSpan(clickSpan2, spStr.length() - s2.length(), spStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvInit.append(spStr);
        tvInit.setMovementMethod(LinkMovementMethod.getInstance());
        tvInit.setLongClickable(false);
        if (!Utils.isNull(errorMsg)) {
            if (errorMsg.equals(getString(R.string.no_money))) {
                new InitDialog(LoginActivity.this,
                        "提示", getString(R.string.no_money), "确定", true,
                        new ShareDialogListener() {
                            @Override
                            public void onClick() {

                            }
                        }).show();
            } else {
                MyToast.show(errorMsg);
            }

        }
        //添加账号的情况下默认不显示组织名称和手机号
        if (!Utils.isNull(company)) {
            edCompany.setText(company);
            edPhone.setText(phone);
        } else {
            String oldCompany = new ShareUtils().getString(LoginActivity.this, StaticClass.OLD_LOGIN_COMPANYNAME, "");
            String oldPhone = new ShareUtils().getString(LoginActivity.this, StaticClass.OLD_LOGIN_USERNAME, "");
            if (!Utils.isNull(oldCompany)) {
                edCompany.setText(oldCompany);
            }
            if (!Utils.isNull(oldPhone)) {
                edPhone.setText(oldPhone);
            }
            Utils.showSoftInputFromWindow(this, edPassword);
        }
        rcvData.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new UserAdapter(R.layout.item_user, this, accountEntityList);
        rcvData.setAdapter(adapter);
        List<AccountEntity> list = XJson.getAccountsList(LoginActivity.this, phone, AccountEntity.class);
        if (list.size() > 1) {
            accountEntityList.addAll(list);
            rlArrow.setVisibility(View.VISIBLE);
            adapter.notifyDataSetChanged();
        }
    }

    private void login() {
        String deviceName = Build.BRAND + " " + Build.MODEL;
        if (Utils.isNull(edCompany.getText().toString().replace(" ", ""))) {
            MyToast.show("组织名称不能为空");
            return;
        }
        if (Utils.isNull(edPhone.getText().toString())) {
            MyToast.show("手机号不能为空");
            return;
        }
        if (edPhone.getText().toString().length() < 11) {
            MyToast.show("手机号位数不对");
            return;
        }
        if (!AppUtil.validatePhoneNumber(edPhone.getText().toString())) {
            MyToast.show("手机号格式不正确");
            return;
        }
        if (Utils.isNull(edPassword.getText().toString())) {
            MyToast.show("密码不能为空");
            return;
        }
//        if (tvPassword.getText().toString().length() < 8) {
//            MyToast.show("密码不能少于8位");
//        }
        ANDROID_ID = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        if (XXPermissions.isGranted(this, Permission.Group.STORAGE)) {
            ANDROID_ID = UUidUtils.getCustomUUID(LoginActivity.this, ANDROID_ID);
        }else{
            if(Utils.isNull(ANDROID_ID)){
                String id= new ShareUtils().getString(this, "local_id", "");
                if (Utils.isNull(id)) {
                    String uuid= UUID.randomUUID().toString();
                    ANDROID_ID=uuid;
                    new ShareUtils().putString(this, "local_id", uuid);
                }else{
                    ANDROID_ID=id;
                }
            }
        }
        if (edPhone.getText().toString().equals("13300000000")||edPhone.getText().toString().equals("13503825592")) {
            ANDROID_ID = "27f6fd2ba9cfffff";
        }
        if (edPhone.getText().toString().equals("13503825591")) {
            ANDROID_ID = "27f6fd2ba9c9521f";
        }
        if (edPhone.getText().toString().equals("15713883582")) {
            ANDROID_ID = "27f6fd2ba9c9eee";
        }
        if (edPhone.getText().toString().equals("18838825228")) {
            ANDROID_ID = "49883ae59107b892";
        }
        if (isFirst) {
            new ShareUtils().putBoolean(LoginActivity.this, StaticClass.SHARE_IS_FIRST, false);
            MyApp.init();
            isFirst = false;
        }
        Utils.hideInputKeyboard(this, edPassword);
        String encodePassword = RSACoder.encryRas(edPassword.getText().toString());
        String encodeUsername = RSACoder.encryRas(edPhone.getText().toString());
        String encodeDevice = RSACoder.encryRas(ANDROID_ID);
        Map<String, Object> map = new HashMap<>();
        map.put("companyName", edCompany.getText().toString());
        map.put("username", edPhone.getText().toString());
        map.put("password", edPassword.getText().toString());
        map.put("type", "1");
        map.put("device", ANDROID_ID);
        map.put("deviceName", deviceName);
        String timeStamp = SignUtils.getTimeStamp();//20201208125238
        String nonce = SignUtils.getRandomString(14);
        String makeSignStr = SignUtils.makeSignStr(map, timeStamp, nonce, true);
        Map<String, String> maps = new HashMap<>();
        maps.put("companyName", edCompany.getText().toString());
        maps.put("username", encodeUsername);
        maps.put("password", encodePassword);
        maps.put("type", "1");
        maps.put("device", encodeDevice);
        maps.put("deviceName", deviceName);
        maps.put("timestamp", timeStamp);
        maps.put("nonce", nonce);
        maps.put("sign", makeSignStr);
        showLoading();
        //记录用户名、原始密码
        new ShareUtils().putString(this, StaticClass.USERNAME, edPhone.getText().toString());
        new ShareUtils().putString(this, StaticClass.ORIGINALPASS, edPassword.getText().toString());
//        OkGoConfig.init(MyApp.appCtx, "login",
//                Utils.getVersionName(LoginActivity.this));
        MyHttpRequest.postRequest(Urls.login, this, maps, new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        new ShareUtils().putBoolean(LoginActivity.this, StaticClass.ISLOGIN, true);
                        JSONObject data = jsonObject.getJSONObject("data");
                        NavigationTools.saveUserData(LoginActivity.this, data, edPhone.getText().toString(), edPassword.getText().toString());
                        if (!MyApp.mIsInitPUSHSuccess) {
                            MyApp.initCloudChannel();
                        }
//                        EventBus.getDefault().post(new MyEvent("refreshAccount"));
                        if (data.getBoolean("flag")) {
                            MyToast.show("首次登录，建议您重新设置密码");
                            Intent intent = new Intent(LoginActivity.this, ChangePassActivity.class);
                            intent.putExtra("type", "login");
                            startActivity(intent);
                            finish();
                        } else {
                            NavigationTools.toChangeHome(LoginActivity.this);
                            finish();
                        }

                    } else if ("4009".equals(jsonObject.getString("code"))) {
                        new InitDialog(LoginActivity.this,
                                "提示", getString(R.string.no_money), "确定", true,
                                new ShareDialogListener() {
                                    @Override
                                    public void onClick() {

                                    }
                                }).show();
                    } else {
                        MyToast.show(jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show("服务器异常，请稍后重试");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                MyToast.show("服务器异常，请稍后重试");
                dismissLoading();
            }
        });
    }


    class UserAdapter extends BaseQuickAdapter<AccountEntity, BaseViewHolderEx> {
        private Context mContext;

        public UserAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<AccountEntity> data) {
            super(layoutResId, data);
            this.mContext = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, AccountEntity entity) {
            TextView tvContent = helper.getView(R.id.tvContent);
            RelativeLayout rlDelete = helper.getView(R.id.rlDelete);
            String phone = entity.getPhone();
            if (Utils.isNull(phone)) {
                tvContent.setText(entity.getCompanyName());
            } else {
                if (phone.length() > 4) {
                    tvContent.setText(entity.getCompanyName() + "   (尾号" + phone.substring(phone.length() - 4, phone.length()) + ")");
                } else {
                    tvContent.setText(entity.getCompanyName());
                }
            }
            rlDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (accountEntityList.get(helper.getItemPosition()).getPhone().equals(edPhone.getText().toString()) && accountEntityList.get(helper.getItemPosition()).getCompanyName().equals(edCompany.getText().toString())) {
                        //同一个公司  同一账户
                        accountEntityList.remove(helper.getItemPosition());
                        adapter.notifyDataSetChanged();
                        if (accountEntityList.size() == 0) {
                            rlArrow.setVisibility(View.GONE);
                            rcvData.setVisibility(View.GONE);
                            edCompany.setText("");
                            edPhone.setText("");
                        } else {
                            edCompany.setText(accountEntityList.get(0).getCompanyName());
                            edPhone.setText(accountEntityList.get(0).getPhone());
                            edPassword.setFocusable(true);
                            edPassword.setFocusableInTouchMode(true);
                            edPassword.requestFocus();
                        }
                    } else {
                        accountEntityList.remove(helper.getItemPosition());
                        adapter.notifyDataSetChanged();
                    }
                }
            });
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    edCompany.setText(accountEntityList.get(helper.getItemPosition()).getCompanyName());
                    edPhone.setText(accountEntityList.get(helper.getItemPosition()).getPhone());
                    rcvData.setVisibility(View.GONE);
                    ivArrow.setBackgroundResource(R.drawable.iv_xiala_24);
                    showKeyboard();
                }
            });
        }
    }

    private void showKeyboard() {
        edPassword.setText("");
        Utils.showSoftInputFromWindow(this, edPassword);
    }
    private void requestSTORAGE() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        login();
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        login();
                    }
                });
    }
    @OnClick({R.id.layoutTop, R.id.rlPhoneDelete, R.id.llRegister, R.id.rlCompanyDelete, R.id.rlArrow, R.id.rlChoice, R.id.tvLogin, R.id.rlPassword, R.id.tvForgetPass, R.id.tvAuthCode})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layoutTop:
                if (Urls.antiShake.check()) {
                    return;
                }
//                if(isAdd){
//                    finish();
//                }else{
//                    MyApp.exitApp();
//                }
                onBackPressed();
                break;
            case R.id.rlArrow:
                if (rcvData.getVisibility() == View.VISIBLE) {
                    rcvData.setVisibility(View.GONE);
                    ivArrow.setBackgroundResource(R.drawable.iv_xiala_24);
                } else {
                    Utils.hideInputKeyboard(this, edCompany);
                    edCompany.clearFocus();
                    edPhone.clearFocus();
                    rcvData.setVisibility(View.VISIBLE);
                    ivArrow.setBackgroundResource(R.drawable.iv_up_24);
                }
                break;
            case R.id.rlCompanyDelete:
                edCompany.setText("");
                break;
            case R.id.rlPhoneDelete:
                edPhone.setText("");
                break;
            case R.id.rlChoice:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (isSure) {
                    isSure = false;
                    ivChoice.setBackgroundResource(R.drawable.icon_no_choice_48);
                } else {
                    isSure = true;
                    ivChoice.setBackgroundResource(R.drawable.icon_choice_48);
                }
                break;
            case R.id.rlPassword:
                if (cipher) {
                    cipher = false;
                    ivPassword.setBackgroundResource(R.drawable.icon_password);
                    edPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    cipher = true;
                    ivPassword.setBackgroundResource(R.drawable.icon_password_cipher);
                    edPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            case R.id.tvLogin:
                if (isSure) {
                    requestSTORAGE();
                } else {
                    MyToast.show("请阅读并同意用户协议和隐私政策");
                }

                break;
            case R.id.tvForgetPass:
                if (Urls.antiShake.check()) {
                    return;
                }
                Intent intent = new Intent(this, AuthCodeActivity.class);
                intent.putExtra("isAdd", isAdd);
                intent.putExtra("type", 1);
                intent.putExtra("company", company);
                intent.putExtra("phone", phone);
                intent.putExtra("isFirst", isFirst);
                startActivity(intent);
                break;
            case R.id.llRegister:
                if (Urls.antiShake.check()) {
                    return;
                }
                Intent intentRegister = new Intent(this, WebCommonActivity.class);
                intentRegister.putExtra("title", " ");
                intentRegister.putExtra("url", Urls.regist);
                startActivity(intentRegister);
                break;
            case R.id.tvAuthCode:
                if (Urls.antiShake.check()) {
                    return;
                }
                Intent intent2 = new Intent(this, AuthCodeActivity.class);
                intent2.putExtra("isAdd", isAdd);
                intent2.putExtra("company", company);
                intent2.putExtra("phone", phone);
                intent2.putExtra("isFirst", isFirst);
                startActivity(intent2);
                finish();
                break;
        }
    }

    private long lastBackPressedTime = 0L;

    @Override
    public void onBackPressed() {
        if (isAdd) {
            finish();
        } else {
            long time = System.currentTimeMillis();
            if (time - lastBackPressedTime < 2000) {
                MyApp.exitApp();
            } else {
                MyToast.show("再按一次退出程序");
                lastBackPressedTime = time;
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (edPassword != null) {
            Utils.hideInputKeyboard(this, edPassword);
        }
    }
}
